/*
 * Copyright (c) GoKeep by gokeep.org. 2022-2023. All rights reserved
 */
package org.gokeep.application.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.gokeep.application.service.AuthService;
import org.gokeep.common.dto.TokenPayload;
import org.gokeep.common.util.UserContext;
import org.gokeep.common.component.TokenComponent;
import org.gokeep.common.config.properties.AuthProperties;
import org.gokeep.common.document.User;
import org.gokeep.common.dto.AuthDto;
import org.gokeep.common.exception.GoKeepException;
import org.gokeep.common.repository.UserRepository;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author xuning
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private UserRepository userRepository;

    @Resource
    private TokenComponent tokenComponent;

    @Resource
    private AuthProperties authProperties;

    @Override
    public String auth(AuthDto authDto) {
        String inputUsername = authDto.getUsername();
        String inputPassword = authDto.getPassword();
        assert inputUsername != null : "username is null";
        assert inputPassword != null : "password is null";
        // TODO: 这里开始对验证码进行验证，从缓存数据中查找验证数据是否匹配
        assert verifyCaptcha(authDto.getCaptcha()) : "验证码输入不正确";
        Optional<User> optional = userRepository.findByUsername(inputUsername);
        assert optional.isPresent() : new GoKeepException("username or password is null", "用户名或密码不正确");
        User user = optional.get();
        assert BCrypt.checkpw(inputPassword, user.getPassword()) : new GoKeepException("username or password is null", "用户名或密码不正确");
        TokenPayload payload = new TokenPayload();
        payload.setUserId(user.getUserId()).setUsername(user.getUsername()).setClientType(authDto.getClientType());
        return tokenComponent.generateToken(payload);
    }

    /**
     * 验证验证码是否正确
     * @return
     */
    private boolean verifyCaptcha(String captcha) {
        // 如果没有启动验证码校验，则直接跳过
        if (!authProperties.isHasCaptcha()) {
            return true;
        }
        String userId = UserContext.getUserId();
        String username = UserContext.getUsername();
        log.info("User[{}:{}] input captcha is: {}", userId, username, captcha);
        return true;
    }
}
